const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

// 创建测试文件
const testFilePath = './test_upload.txt';
fs.writeFileSync(testFilePath, '这是一个测试文件内容，用于测试upload_to_oss接口');

async function testUpload() {
  try {
    const formData = new FormData();
    formData.append('file', fs.createReadStream(testFilePath));
    
    console.log('开始测试upload_to_oss接口...');
    
    const response = await axios.post('http://localhost:9000/upload-to-oss', formData, {
      headers: {
        ...formData.getHeaders(),
      },
    });
    
    console.log('✅ 上传成功:', response.data);
    
  } catch (error) {
    if (error.response) {
      console.log('❌ 上传失败:', error.response.status, error.response.data);
    } else {
      console.log('❌ 请求错误:', error.message);
    }
  } finally {
    // 清理测试文件
    if (fs.existsSync(testFilePath)) {
      fs.unlinkSync(testFilePath);
    }
  }
}

// 测试IP限流
async function testRateLimit() {
  console.log('\n开始测试IP限流功能...');
  
  for (let i = 1; i <= 6; i++) {
    try {
      const formData = new FormData();
      const smallFilePath = `./test_small_${i}.txt`;
      fs.writeFileSync(smallFilePath, `测试文件 ${i}`);
      
      formData.append('file', fs.createReadStream(smallFilePath));
      
      const response = await axios.post('http://localhost:9000/upload-to-oss', formData, {
        headers: {
          ...formData.getHeaders(),
        },
      });
      
      console.log(`✅ 第${i}次上传成功`);
      fs.unlinkSync(smallFilePath);
      
    } catch (error) {
      if (error.response && error.response.status === 429) {
        console.log(`❌ 第${i}次上传被限流:`, error.response.data.message);
        break;
      } else {
        console.log(`❌ 第${i}次上传失败:`, error.message);
      }
    }
    
    // 添加一点延迟
    await new Promise(resolve => setTimeout(resolve, 100));
  }
}

// 测试文件大小限制
async function testFileSizeLimit() {
  console.log('\n开始测试文件大小限制...');
  
  // 创建一个大文件（6MB）
  const largeFilePath = './test_large.txt';
  const largeContent = 'x'.repeat(6 * 1024 * 1024); // 6MB
  fs.writeFileSync(largeFilePath, largeContent);
  
  try {
    const formData = new FormData();
    formData.append('file', fs.createReadStream(largeFilePath));
    
    const response = await axios.post('http://localhost:9000/upload-to-oss', formData, {
      headers: {
        ...formData.getHeaders(),
      },
    });
    
    console.log('✅ 大文件上传成功（不应该发生）');
    
  } catch (error) {
    if (error.response && error.response.status === 400) {
      console.log('✅ 大文件上传被正确拒绝:', error.response.data.message);
    } else {
      console.log('❌ 文件大小限制测试失败:', error.message);
    }
  } finally {
    if (fs.existsSync(largeFilePath)) {
      fs.unlinkSync(largeFilePath);
    }
  }
}

async function runTests() {
  console.log('🚀 开始测试upload_to_oss接口功能\n');
  
  await testUpload();
  await testRateLimit();
  await testFileSizeLimit();
  
  console.log('\n🎉 测试完成！');
}

runTests().catch(console.error);